import pymysql
# 封装数据库工具类
class DBUtil(object):
    conn = None

    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="localhost",
                                       port=3306,
                                       user="root",
                                       password="123456",
                                       database="test_db",
                                       charset="utf8")
        return cls.conn

    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    # 常用方法：查询一条
    @classmethod
    def select_one(cls, sql):
        cursor = None
        res = None
        try:
            #建立连接
            cls.cnn = cls.__get_conn()

            #获取游标
            cursor = cls.conn.cursor()

            #执行查询语句
            cursor.execute(sql)

            #提取一条结果
            res = cursor.fetchone()

        except Exception as e:
            print("查询sql错误：", e)

        finally:
            cursor.close()
            cls.__close_conn()
            return res


if __name__ == '__main__':
    res = DBUtil.select_one("select * from employees;")
    print("查询结果为：", res)